$(document).ready(function(){
  function drawCard(target, rank, suit, width, front) {
    if (width != null) {
      target.css({
        'width': width,
        'font-size': width * 12.5 / 200
      });
    }

    target.addClass('card');
    target.attr('card', target.attr('id'));

    new PlayingCards.CardView({
      el: target,
      model: new PlayingCards.CardModel({
        rank: PlayingCards.RANK[rank],
        suit: PlayingCards.SUIT[suit],
        front: front
      }),
      templates: new PlayingCards.Templates()
    }).render();
  }

  function clearHand(player) {
    if (player == 0 || player == 1 ||
        player == 2 || player == 3) {
      $("div#p" + player).html('<div id="p' + player + '-card-0"></div>' +
                            '<div id="p' + player + '-card-1"></div>' +
                            '<div id="p' + player + '-card-2"></div>' +
                            '<div id="p' + player + '-card-3"></div>' +
                            '<div id="p' + player + '-card-4"></div>');
    }
  }

  function moveCardUp(player, card) {
    var key = "margin";
    var val = "0px";
    if (player == 0) {
      key = "margin-top";
      val = "-30px";
    }
    else if (player == 1) {
      key = "margin-left";
      val = "30px";
    }
    else if (player == 2) {
      key = "margin-top";
      val = "30px";
    }
    else if (player == 3) {
      key = "margin-left";
      val = "-30px";
    }
    if (player == 0 || player == 1 ||
        player == 2 || player == 3) {
      $("[card='p" + player + "-card-" + card + "']").css(key, val);
    }
  }

  function moveCardDown(player, card) {
    var key = "margin";
    if (player == 0) {
      key = "margin-top";
    }
    else if (player == 1) {
      key = "margin-left";
    }
    else if (player == 2) {
      key = "margin-top";
    }
    else if (player == 3) {
      key = "margin-left";
    }
    if (player == 0 || player == 1 ||
        player == 2 || player == 3) {
      $("[card='p" + player + "-card-" + card + "']").css(key, "0px");
    }
  }

  function drawCards(player, cards, show) {
    if (player == 0) {
      for (var i=0; i < (cards.length > 5 ? 5 : cards.length); i++)
      {
        drawCard($('#p0-card-' + i), cards[i]["rank"], cards[i]["suit"], 80, show);
      }
    }
    else if (player == 1) {
      for (var i=0; i < (cards.length > 5 ? 5 : cards.length); i++)
      {
        drawCard($('#p1-card-' + i), cards[i]["rank"], cards[i]["suit"], 80, show);
        $("[card='p1-card-" + i + "']").css("transform", "rotate(90deg)");
        if (i > 0) {
          $("[card='p1-card-" + i + "']").css({
            "transform": "rotate(90deg)",
            "margin-top": "-90px"
          });
        }
      }
    }
    else if (player == 2) {
      for (var i=0; i < (cards.length > 5 ? 5 : cards.length); i++)
      {
        drawCard($('#p2-card-' + i), cards[i]["rank"], cards[i]["suit"], 80, show);
      }
    }
    else if (player == 3) {
      for (var i=0; i < (cards.length > 5 ? 5 : cards.length); i++)
      {
        drawCard($('#p3-card-' + i), cards[i]["rank"], cards[i]["suit"], 80, show);
        $("[card='p3-card-" + i + "']").css("transform", "rotate(90deg)");
          $("[card='p3-card-" + i + "']").css({
            "transform": "rotate(90deg)",
            "z-index": (i + 2)
          });
          if (i < 4) {
            $("[card='p3-card-" + i + "']").css({
              "margin-top": "-90px",
            });
          }
      }
    }
  }

  function consoleMsg(type, text) {
    if (type == "normal") {
      $("#console tbody").append('<tr><td>' + text + '</td></tr>');
    }
    else if (type == "success") {
      $("#console tbody").append('<tr class="success"><td>' + text + '</td></tr>');
    }
    else if (type == "warning") {
      $("#console tbody").append('<tr class="warning"><td>' + text + '</td></tr>');
    }
    else if (type == "danger") {
      $("#console tbody").append('<tr class="danger"><td>' + text + '</td></tr>');
    }
    $("#console tbody").scrollTop($("#console tbody").scrollTop() + 100);
  }

  function vanishPlayer(player) {
    if (player == 0) {
      clearHand(0);
      $("span#l0").hide();
    }
    else if (player == 1) {
      clearHand(1);
      $("span#l1").hide();
    }
    else if (player == 2) {
      clearHand(2);
      $("span#l2").hide();
    }
    else if (player == 3) {
      clearHand(3);
      $("span#l3").hide();
    }
  }

  function showPlayer(player, name) {
    if (player == 0) {
      $("span#l0").text(name);
      $("span#l0").show();
    }
    else if (player == 1) {
      $("span#l1").text(name);
      $("span#l1").show();
    }
    else if (player == 2) {
      $("span#l2").text(name);
      $("span#l2").show();
    }
    else if (player == 3) {
      $("span#l3").text(name);
      $("span#l3").show();
    }
  }

  function changeTurn(player) {
    $("button#exchenge").prop('disabled', true);
    $("span[id^='l']").each(function( index ) {
      $(this).attr("class", "label label-default");
    });
    if (player == 0) {
      $("span#l0").removeClass("label-default");
      $("span#l0").addClass("label-success");
      $("span#status").attr("class", "glyphicon glyphicon-circle-arrow-down");
      $("button#exchange").prop('disabled', false);
    }
    else if (player == 1) {
      $("span#l1").removeClass("label-default");
      $("span#l1").addClass("label-success");
      $("span#status").attr("class", "glyphicon glyphicon-circle-arrow-left");
    }
    else if (player == 2) {
      $("span#l2").removeClass("label-default");
      $("span#l2").addClass("label-success");
      $("span#status").attr("class", "glyphicon glyphicon-circle-arrow-up");
    }
    else if (player == 3) {
      $("span#l3").removeClass("label-default");
      $("span#l3").addClass("label-success");
      $("span#status").attr("class", "glyphicon glyphicon-circle-arrow-right");
    }
  }

  drawCards(
    0,
    [
      {"rank": "ten", "suit": "diamond"},
      {"rank": "king", "suit": "spade"},
      {"rank": "two", "suit": "diamond"},
      {"rank": "two", "suit": "spade"},
      {"rank": "six", "suit": "spade"},
    ],
    true
  );

  drawCards(
    1,
    [
      {"rank": "ten", "suit": "diamond"},
      {"rank": "king", "suit": "spade"},
      {"rank": "two", "suit": "diamond"},
      {"rank": "two", "suit": "spade"},
      {"rank": "six", "suit": "spade"},
    ],
    false
  );

  drawCards(
    2,
    [
      {"rank": "ten", "suit": "diamond"},
      {"rank": "king", "suit": "spade"},
      {"rank": "two", "suit": "diamond"},
      {"rank": "two", "suit": "spade"},
      {"rank": "six", "suit": "spade"},
    ],
    false
  );

  drawCards(
    3,
    [
      {"rank": "ten", "suit": "diamond"},
      {"rank": "king", "suit": "spade"},
      {"rank": "two", "suit": "diamond"},
      {"rank": "two", "suit": "spade"},
      {"rank": "six", "suit": "spade"},
    ],
    false
  );

  var movedCards = [];
  var myTurn = false;
  var players = [true, true, true, true];

  $("[card^='p0']").on("click", function(e){
  	if (myTurn) {
	  	var c = parseInt($(this).attr("card").charAt($(this).attr("card").length - 1));
      var pos = movedCards.indexOf(c);
	  	if (pos == -1) {
	  			if (movedCards.length < 4) {
		  		moveCardUp(0, c);
		  		movedCards.push(c);
	  		}
	  	}
	  	else {
	  		movedCards.splice(pos, 1);
        moveCardDown(0, c);
	  	}
	}
  });

  $("#console tbody").scrollTop($("#console tbody").scrollTop() + 550);

  var ws = $.websocket("@play.Play.application().configuration().getString("webSocketUrl")@uuid", {
    open: function() {
      consoleMsg("success", "Connection established.");
    },
    close: function() {
      consoleMsg("danger", "Connection closed.");
    },
    events: {
      say: function(e) {
        alert(e.data.name);
        alert(e.data.text);
      }
    }
  });

});